﻿/*
 * ========================================================================
 * Copyright(c) 2008-2010北京高阳金信信息技术有限公司, All Rights Reserved.
 * ========================================================================
 * 类型转换
 * 
 * 作者：周燕龙     时间：2010-03-8
 * 版本：V1.0
 * 
 * 修改者：         时间：                
 * 修改说明：
 * ========================================================================
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Globalization;

namespace Hisuntech.SystemFramework.Web
{
    public class Serializer
    {

        /// <summary>
        /// 将指定类型转化为xml文本
        /// </summary>
        /// <param name="objectToConvert">需要转换的数据</param>
        /// <returns>xml文本数据</returns>
        public static string ConvertToString(object objectToConvert)
        {
            string xml = null;

            if (objectToConvert != null)
            {
                //得到序列化的类型
                Type t = objectToConvert.GetType();

                XmlSerializer ser = new XmlSerializer(t);

                using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                {
                    ser.Serialize(writer, objectToConvert);
                    xml = writer.ToString();
                    writer.Close();
                }
            }

            return xml;
        }

        /// <summary>
        /// 将xml文件转化为指定类型
        /// </summary>
        /// <param name="xml">xml类型数据</param>
        /// <param name="objectType">指定转化的类型</param>
        /// <returns>指定的类型</returns>
        public static object ConvertToObject(string xml, Type objectType)
        {
            object convertedObject = null;

            if (!string.IsNullOrEmpty(xml))
            {
                using (StringReader reader = new StringReader(xml))
                {
                    XmlSerializer ser = new XmlSerializer(objectType);
                    convertedObject = ser.Deserialize(reader);
                    reader.Close();
                }
            }
            return convertedObject;
        }
    }
}
